import { App, ref, UnwrapRef } from "vue";
import type { ModuleInterface, ModuleConfig, SendCmd } from "./common/index";
import type { Response } from "./common/index";
import { SEND_CALIBRATION_CMD_KEY, GET_CALIBRATION_DATA_KEY } from "./common/index";
import { useCalibrationStore } from "./store/calibrationStore";

import CalibrationForm from "./components/index.vue";

const moduleInfo: ModuleConfig = {
  moudleType: "CalibrationForm",
  name: "校准模块",
  version: "1.0.0",
  description: "校准模块"
};

class CalibrationModule<
  EventData extends object = object, // 约束为对象，解决 Object.assign 问题
  CmdParams = any,
  Return = Response<any> // 泛型 Response
> implements ModuleInterface<EventData, CmdParams, Return> {

  _moduleInfo = moduleInfo;
  private _eventData: UnwrapRef<EventData>;
  private sendCmd: SendCmd<CmdParams, Return>;

  constructor(sendCmd: SendCmd<CmdParams, Return>, initialData: EventData = {} as EventData) {
    this._eventData = ref(initialData) as unknown as UnwrapRef<EventData>;
    this.sendCmd = sendCmd;
  }

  sendCommand(cmd: string, cmdParams?: CmdParams): Return | Promise<Return> {
    console.log("发送指令：", cmd, cmdParams);
    return this.sendCmd(this._moduleInfo.moudleType, cmd, cmdParams);
  }

  install(app: App): void {

    app.component("CalibrationForm", CalibrationForm);

    app.provide(GET_CALIBRATION_DATA_KEY, () => this.eventData);

    app.provide(SEND_CALIBRATION_CMD_KEY, (cmd: string, cmdParams?: CmdParams): Return | Promise<Return> => {
      console.log("插件内部转发指令：", cmd, cmdParams);
      return this.sendCommand(cmd, cmdParams);
    });
  }

  get eventData(): EventData {
    return this._eventData as EventData;
  }

  dataEvent(data: Partial<EventData>): void {
    Object.assign(this._eventData as Object, data);
  }

  async startup(): Promise<void> {

    // 2. 实例化组合式 store
    const calibrationStore = useCalibrationStore();

    // 修复参数错误：直接传递 { sendCalibCmd } 而不是 { injections: sendCalibCmd }
    if (!calibrationStore.sendCalibrationCmd) {
      console.log("Pinia 中未存储 sendCalibrationCmd,进行存储");
      calibrationStore.setInjections({
        sendCalibrationCmd: (cmd: string, cmdParams?: CmdParams) => this.sendCommand(cmd, cmdParams)
      });
    }

    console.log("插件根组件获取到 sendCalibrationCmd,初始化成功", calibrationStore.sendCalibrationCmd); // 先确认这个值是否为函数

    // 验证存储结果
    console.log("存储后 Pinia 中的值：", calibrationStore.sendCalibrationCmd);
    console.log("校准模块初始化完成");
  }
}

export const createCalibrationModule = <
  EventData extends object = object,
  CmdParams = any,
  Return = Response<any>
>(
  sendCmd: SendCmd<CmdParams, Return>,
  initialData: EventData
): ModuleInterface<EventData, CmdParams, Return> => {
  return new CalibrationModule<EventData, CmdParams, Return>(sendCmd, initialData);
};

export { CalibrationForm };
